<?php

namespace Itdashu\SwoftThirdPartyService\Service\Base;

/**
 * PKCS7算法 - 加解密
 * Class PKCS7Encoder
 */
class PKCS7Encoder
{

  public static $blockSize = 32;

  /**
   * 对需要加密的明文进行填充补位
   * @param string $text 需要进行填充补位操作的明文
   * @return string 补齐明文字符串
   */
  public static function encode($text): string
  {
    $amountToPad = self::$blockSize - (strlen($text) % self::$blockSize);
    if ($amountToPad === 0) {
      $amountToPad = self::$blockSize;
    }
    [$pad_chr, $tmp] = [chr($amountToPad), ''];
    for ($index = 0; $index < $amountToPad; $index++) {
      $tmp .= $pad_chr;
    }
    return $text . $tmp;
  }

  /**
   * 对解密后的明文进行补位删除
   * @param string $text 解密后的明文
   * @return string 删除填充补位后的明文
   */
  public static function decode($text): string
  {
    $pad = ord(substr($text, -1));
    if ($pad < 1 || $pad > self::$blockSize) {
      $pad = 0;
    }
    return substr($text, 0, strlen($text) - $pad);
  }

}